#!/usr/bin/env bash

# This script must be run within the ClojureScript top-level project
# directory.

set -e

if [[ -z "$CLJS_SCRIPT_QUIET" ]]; then
  set -x
fi

rm -f resources/brepl_client.js

# The command `git describe --match v0.0` will return a string like
#
# v0.0-856-g329708b
#
# where 856 is the number of commits since the v0.0 tag. It will always
# find the v0.0 tag and will always return the total number of commits (even
# if the tag is v0.0.1).
MAJOR="1"
MINOR="10"
REVISION=`git --no-replace-objects describe --match v$MAJOR.$MINOR`

# Extract the version number from the string.
REVISION_REGEX="v[0-9]*\.[0-9]*-([0-9]*)-.*"
if [[ $REVISION =~ $REVISION_REGEX ]]
then
  REVISION="${BASH_REMATCH[1]}"
fi

COMP_FILE=`mktemp /tmp/compiler.clj.XXXXXXXXXXX`
sed -e 's/^.def ^:dynamic \*clojurescript-version\*.*$/(def ^:dynamic *clojurescript-version* {:major '"$MAJOR"', :minor '"$MINOR"', :qualifier '"$REVISION"'})/' src/main/clojure/cljs/util.cljc > $COMP_FILE
mv $COMP_FILE src/main/clojure/cljs/util.cljc

CLJS_FILE=`mktemp /tmp/core.cljs.XXXXXXXXXXX`
sed -e 's/^.def \*clojurescript-version\*.*$/(def *clojurescript-version* '\""$MAJOR.$MINOR.$REVISION"\"')/' src/main/cljs/cljs/core.cljs > $CLJS_FILE
mv $CLJS_FILE src/main/cljs/cljs/core.cljs

rm -f src/main/cljs/cljs/core.aot.js
rm -f src/main/cljs/cljs/core.aot.js.map
rm -f src/main/cljs/cljs/core.cljs.cache.aot.edn
rm -f src/main/cljs/cljs/core.cljs.cache.aot.json

./script/aot_core

AOT_FILE=`mktemp /tmp/core.aot.js.XXXXXXXXXXX`
sed -e "s/0.0.0000/$MAJOR.$MINOR.$REVISION/" src/main/cljs/cljs/core.aot.js > $AOT_FILE
mv $AOT_FILE src/main/cljs/cljs/core.aot.js

AOT_CACHE_FILE=`mktemp /tmp/core.cljs.cache.aot.edn.XXXXXXXXXXX`
sed -e "s/0.0.0000/$MAJOR.$MINOR-$REVISION/" src/main/cljs/cljs/core.cljs.cache.aot.edn > $AOT_CACHE_FILE
mv $AOT_CACHE_FILE src/main/cljs/cljs/core.cljs.cache.aot.edn

clojure -X:uberjar :jar target/cljs.jar :compile-ns :all

rm -f src/main/cljs/cljs/core.aot.js
rm -f src/main/cljs/cljs/core.aot.js.map
rm -f src/main/cljs/cljs/core.cljs.cache.aot.edn
rm -f src/main/cljs/cljs/core.cljs.cache.aot.json
